<template>
  <el-dialog
    v-model="dialogTableVisible"
    :title="title"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    :show-close="false"
    :draggable="true"
    @before-close="() => false"
    append-to-body
    style="width: 70%"
  >
    <FormBase :mode="mode" @on-submit="onSubmit" @on-cancel="handleClose">
      <div class="editor-container">
        <el-tabs type="border-card" v-model="activeName">
          <el-tab-pane label="基础信息" name="1">
            <el-form
              ref="expertForm"
              :model="dataModel"
              label-width="auto"
              :rules="rules"
              style="width: 100%"
            >
              <el-form-item :label="t('专家名称')" prop="name">
                <el-input
                  v-model="dataModel.name"
                  :maxlength="10"
                  :show-word-limit="true"
                  clearable
                  :disabled="mode === 'view'"
                />
              </el-form-item>
              <el-form-item :label="t('专家职级')" prop="title">
                <el-input
                  v-model="dataModel.title"
                  :maxlength="10"
                  :show-word-limit="true"
                  clearable
                  :disabled="mode === 'view'"
                />
              </el-form-item>
              <el-form-item :label="t('专家专业')" prop="major">
                <el-input
                  v-model="dataModel.major"
                  :maxlength="10"
                  :show-word-limit="true"
                  clearable
                  :disabled="mode === 'view'"
                />
              </el-form-item>
              <el-form-item :label="t('专家介绍')" prop="introduction">
                <el-input
                  v-model="dataModel.introduction"
                  type="textarea"
                  :maxlength="500"
                  :show-word-limit="true"
                  :rows="3"
                  clearable
                  :disabled="mode === 'view'"
                />
              </el-form-item>
              <el-form-item :label="t('专家头像')" prop="originImg">
                <VImage
                  ref="uploadImage"
                  :src="dataModel.originImg"
                  :autoUpload="false"
                  fit="contain"
                  :disabled="mode === 'view'"
                  @onUploaded="onUploaded"
                >
                </VImage>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="荣誉" name="2">
            <el-scrollbar height="500px">
              <el-row :gutter="10" style="width: 98%">
                <el-col
                  style="margin-bottom: 10px"
                  :span="6"
                  v-for="(v, index) in prizeDots"
                  :key="v.objectId"
                >
                  <el-card v-if="!v.isEditable">
                    <template #header>
                      <span style="display: block; height: 20px; text-wrap: nowrap">{{
                        v.name
                      }}</span>
                    </template>
                    <VImage
                      :src="v.originImg"
                      :disabled="true"
                      fit="contain"
                      :style="{ height: '160px', width: '100%' }"
                    ></VImage>
                    <div></div>
                    <template #footer>
                      <span
                        style="
                          display: block;
                          height: 20px !important;
                          width: 100%;
                          text-wrap: nowrap;
                        "
                        >{{ v.description }}</span
                      >
                      <div
                        style="
                          display: flex;
                          align-items: center;
                          justify-content: center;
                          padding: 10px 0 0 0;
                        "
                      >
                        <el-button
                          type="primary"
                          :icon="EditPen"
                          circle
                          @click="handleEditPrizeDot(index)"
                        ></el-button>
                        <el-button circle :icon="Delete" @click="handleDelPrize(index)"></el-button>
                      </div>
                    </template>
                  </el-card>
                  <el-card v-else>
                    <template #header>
                      <el-input
                        v-model="v.name"
                        :maxlength="20"
                        :show-word-limit="true"
                        clearable
                        :placeholder="t('请输入奖项名称')"
                      />
                    </template>
                    <VImage
                      ref="pdUploadImage"
                      :src="v.originImg"
                      :autoUpload="true"
                      :style="{ height: '160px', width: '100%' }"
                      fit="contain"
                      @on-uploaded="
                        (result) => {
                          v.originImg = result.path
                        }
                      "
                    >
                    </VImage>

                    <template #footer>
                      <el-input
                        v-model="v.description"
                        type="textarea"
                        :maxlength="128"
                        :show-word-limit="true"
                        :rows="2"
                        clearable
                        :placeholder="t('请输入奖项描述')"
                      />
                      <div
                        style="
                          display: flex;
                          align-items: center;
                          justify-content: center;
                          padding: 10px 0 0 0;
                        "
                      >
                        <el-button
                          type="primary"
                          :icon="Check"
                          circle
                          @click="handleModifyPrizeDot(index)"
                        ></el-button>
                        <el-button
                          :icon="Close"
                          circle
                          @click="
                            () => {
                              v.isEditable = false
                            }
                          "
                        ></el-button>
                      </div>
                    </template>
                  </el-card>
                </el-col>
                <el-col style="margin-bottom: 10px" :span="6">
                  <el-card style="height: 365px">
                    <VPlusButton
                      @click="handleAddPrizeDot"
                      :style="{ width: '100%', height: '325px' }"
                    />
                  </el-card>
                </el-col>
              </el-row>
            </el-scrollbar>
          </el-tab-pane>
          <el-tab-pane label="课程" name="3" v-if="mode !== 'add'">
            <div style="padding: 0 0 10px 0">
              <el-button type="primary" @click="handleAddCourse">{{ t('添加') }}</el-button>
              <el-button type="default" @click="handleRemoveCourse">{{ t('移除') }}</el-button>
            </div>
            <el-table
              ref="courseTableRef"
              :data="tableDataCourse"
              :border="true"
              header-row-class-name="table-header"
              height="400"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="name" :label="t('名称')" width="180" />
              <el-table-column prop="categoryText" :label="t('分类')" width="180" />
              <el-table-column prop="originImg" :label="t('封面')">
                <template #default="scope">
                  <v-image
                    :src="scope.row.originImg"
                    :style="{ width: '45px', height: '45px' }"
                    :disabled="true"
                  ></v-image>
                </template>
              </el-table-column>
              <el-table-column prop="likes" :label="t('点赞数')"> </el-table-column>
              <el-table-column prop="joins" :label="t('学习人数')"> </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>
    </FormBase>
  </el-dialog>
  <ExpertCourseSelect
    v-model:show="showCourseSelection"
    v-model="dataModel.courseIds"
    :expertId="dataModel.objectId"
    @on-selected="handleCourseSelected"
  >
  </ExpertCourseSelect>
</template>
<script setup lang="ts">
import { Ref, computed, onMounted, onUnmounted, reactive, ref, unref, watch } from 'vue'
import { t } from '@/common/locale'
import { FormRules } from 'element-plus'
import { add, getExpertCourses, getExpertDetail, getExpertPrizeDots, update } from '@/api/expert'
import { Delete, EditPen, Check, Close } from '@element-plus/icons-vue'
import VImage from '@/components/other/VImage.vue'
import VPlusButton from '@/components/other/VPlusButton.vue'
import elHelper from '@/common/elHelper'
import ExpertCourseSelect from './ExpertCourseSelect.vue'
import FormBase from '../layout/FormBase.vue'
import comFunc from '@/common/comFunc'

const props = defineProps({
  data: {
    type: Object,
    default: {}
  },
  mode: {
    type: String,
    validator: (val: string) => {
      return ['add', 'modify'].includes(val)
    },
    default: 'add'
  },
  show: {
    type: Boolean,
    default: false
  }
})
const emit = defineEmits(['onSubmited', 'update:show'])
const title = computed(() => {
  switch (props.mode) {
    case 'add':
      return t('新增')
    case 'modify':
      return t('修改')
    case 'view':
      return t('查看')
  }
})

const dataModel: ExpertDataModel = reactive({
  name: '',
  major: '',
  introduction: '',
  title: '',
  originImg: '',
  objectId: '',
  thumbImg: '',
  courseIds: [],
  expertPrizeDtos: []
})
Object.assign(dataModel, props.data)
const showCourseSelection = ref(false)
const activeName = ref('1')
const mode = ref(props.mode)
const dialogTableVisible = ref(false)
const expertForm = ref()
const courseTableRef = ref()
const pdUploadImage = ref()
const uploadImage: Ref<typeof VImage | undefined> = ref()
const prizeDots: Ref<any[]> = ref([])
const rules = reactive<FormRules<ExpertDataModel>>({
  name: [{ required: true, message: t('请输入登录账号'), trigger: 'blur' }]
})
const tableDataCourse: Ref<CourseDataModel[]> = ref([])

watch(
  () => props.show,
  async (val) => {
    dialogTableVisible.value = val
    if (val) {
      Object.assign(dataModel, props.data)
      mode.value = props.mode
      await getInfo()
      getPrizeDots()
      getCourseData()
    } else {
      dataModel.introduction = ''
      dataModel.major = ''
      dataModel.name = ''
      dataModel.objectId = ''
      dataModel.originImg = ''
      dataModel.thumbImg = ''
      dataModel.title = ''
      uploadImage.value?.clear()
    }
  }
)
const getPrizeDots = async () => {
  prizeDots.value = []
  if (dataModel.objectId) {
    const re = await getExpertPrizeDots(dataModel.objectId)
    if (re.isSuccess) {
      dataModel.expertPrizeDtos = re.data
      prizeDots.value = re.data || []
      prizeDots.value.forEach((item) => {
        item.isEditable = false
      })
    }
  }
}
const handleAddCourse = () => {
  showCourseSelection.value = true
}
const handleRemoveCourse = () => {
  if (!courseTableRef.value) return
  const rows = courseTableRef.value.getSelectionRows()
  if (rows.length <= 0) {
    elHelper.showErrorMsg('请选择要移除的课程')
    return
  }
  rows.forEach((r) => {
    const index = tableDataCourse.value.findIndex((v) => v.objectId === r.objectId)
    if (index >= 0) tableDataCourse.value.splice(index, 1)
    const indexOfCourseIds = dataModel.courseIds?.findIndex((v) => v === r.objectId) as number
    if (indexOfCourseIds >= 0) dataModel.courseIds?.splice(indexOfCourseIds, 1)
  })
}
const handleCourseSelected = (val: CourseDataModel[]) => {
  val.forEach((item) => {
    if (!tableDataCourse.value.find((v) => v.objectId === item.objectId)) {
      tableDataCourse.value.push(item)
    }
  })
}
const handleAddPrizeDot = () => {
  if (!prizeDots.value.find((v) => v.isEditable)) {
    prizeDots.value.push({
      name: '',
      description: '',
      originImg: '',
      objectId: '',
      isEditable: true
    })
  }
}
const onUploaded = (v: { path: string; remotePath: string }) => {}
const onSubmit = async () => {
  let valid = await expertForm.value.validate((valid) => valid)
  if (valid) {
    const reUpload = await uploadImage.value?.upload()
    if (!reUpload.isSuccess) {
      elHelper.showErrorMsg(reUpload.msg)
      return
    }
    dataModel.originImg = reUpload.path
    dataModel.expertPrizeDtos = []
    prizeDots.value.forEach((item) => {
      dataModel.expertPrizeDtos?.push({
        name: item.name,
        description: item.description,
        objectId: item.objectId,
        originImg: item.originImg,
        expertId: dataModel.objectId
      })
    })
    dataModel.courseIds = []
    tableDataCourse.value.forEach((item) => {
      dataModel.courseIds?.push(comFunc.nvl(item.objectId))
    })
    if (mode.value === 'add') {
      const re = await add(dataModel)
      if (re.isSuccess) {
        emit('onSubmited', re.data!)
        elHelper.showSuccessMsg('操作成功')
        handleClose()
      } else {
        elHelper.showErrorMsg(re.msg)
      }
    } else {
      const re = await update(dataModel)
      if (re.isSuccess) {
        emit('onSubmited', re.data!)
        elHelper.showSuccessMsg('操作成功')
        handleClose()
      } else {
        elHelper.showErrorMsg(re.msg)
      }
    }
  }
}
const handleClose = () => {
  dialogTableVisible.value = false
  emit('update:show', false)
}
const handleDelPrize = (index: number) => {
  prizeDots.value.splice(index, 1)
}
const handleModifyPrizeDot = (index: number) => {
  if (!prizeDots.value[index].name) {
    elHelper.showErrorMsg('奖项名称不能为空')
    return
  }
  prizeDots.value[index].isEditable = false
}
const handleEditPrizeDot = (index: number) => {
  if (prizeDots.value[index]) {
    prizeDots.value[index].isEditable = true
    prizeDots.value.forEach((item, i) => {
      if (i !== index) {
        item.isEditable = false
      }
    })
  }
}

const getCourseData = async () => {
  tableDataCourse.value = []
  const re = await getExpertCourses(comFunc.nvl(dataModel.objectId))
  if (re.isSuccess) {
    tableDataCourse.value = re.data as CourseDataModel[]
  }
}
const getInfo = async () => {
  const re = await getExpertDetail(comFunc.nvl(dataModel.objectId))
  if (re.isSuccess) {
    Object.assign(dataModel, re.data)
  }
}
onUnmounted(() => {
  handleClose()
})
getPrizeDots()
</script>
<style lang="scss" scoped>
.editor-container {
  width: 100%;
}

.btn-container {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px 0 0 0;
}
</style>
